#!/bin/bash -e

# Downloads a package
# Looks into the cache if the package $1 is there
# Otherwise will download using provided link $2.
# The package is then saved to the cache and 
# extracted in provided location $3.

function getPackage	{
	if [ -f "$PATH_PKGCACHE/$1" ]; then
		# we already have this file
		echo	"s" > /dev/null
	else
		# we need to download this
		wget -nv --tries=6 --waitretry=10  \
			$2 -O "$PATH_PKGCACHE/$1"
		mv "./$1" "$PATH_PKGCACHE/$1"
	fi
	
	TDIR=$(mktemp -d)
	pushd "$TDIR" > /dev/null
	if   [[ $1 == *.tar.gz ]]; then
		tar -xzvf "$PATH_PKGCACHE/$1" > /dev/null
		for f in *
		do
			mv -f "./$f" "$3"
			break
		done
	elif [[ $1 == *.tar.bz2 ]]; then
		tar -xvf "$PATH_PKGCACHE/$1"  > /dev/null
		for f in *
		do
			mv -f "./$f" "$3"
			break
		done
	elif [[ $1 == *.tar.xz ]]; then
		tar Jxf "$PATH_PKGCACHE/$1" > /dev/null
		for f in *
		do
			mv -f "./$f" "$3"
			break
		done
	else
		cp "$PATH_PKGCACHE/$1" "$3"
	fi
	popd > /dev/null
	
	# delete temporary directory
	rm -rfv "$TDIR" > /dev/null
}

function getCachedPackage	{
	#echo	"   getCachedPackage $1"


	EXTRACT_TAR=$JAIL_PATH/build-dir/tmp

	if [ -f "$PATH_PKGCACHE/$1.tar.bz2" ]; then
		TAR_OPTS="jxf"
		TAR_IN="$PATH_PKGCACHE/$1.tar.bz2"
	elif [ -f "$PATH_PKGCACHE/$1.tar.gz" ]; then
		TAR_OPTS="-zxf"
		TAR_IN="$PATH_PKGCACHE/$1.tar.gz"
	elif [ -f "$PATH_PKGCACHE/$1.tar.xz" ]; then
		TAR_OPTS="-Jxf"
		TAR_IN="$PATH_PKGCACHE/$1.tar.xz"
	else
		echo	"ERROR!!! Unknown tar type: $CRTPKG"
		exit -1
	fi

	mkdir $EXTRACT_TAR
	
	# extract and place sources in designated directory
	pushd "$EXTRACT_TAR" > /dev/null
	echo	"    Extracting $TAR_IN in $EXTRACT_TAR..."
	echo	"    Will be transferred to $2"
	tar $TAR_OPTS $TAR_IN > /dev/null
	for f in *
	do
		mv -f "./$f" "$2"
		break
	done
	popd > /dev/null
	
	# remove temporary directory for tar
	rm -rfv $EXTRACT_TAR > /dev/null

}
